package com.example.demo.LeetCode.list;

public class GetKthFromEnd {
    //倒数第k个元素 index =  n - k + 1
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode p1 = head;
        //p1先走k步
        for (int i = 0 ;i < k ; i++){
            p1 = p1.next;
        }
        ListNode p2 = head;
        //p1和p2同时走n-k步
        while(p1 != null){
            p1 = p1.next;
            p2 = p2.next;
        }
        return p2;
    }
}
